// 1. React核心库
import React, { useState, useEffect ,useRef } from 'react';

// 2. UI组件库 - 按字母顺序
import { Card, Col, Row, Statistic, Tag, Select } from 'antd';

// 3. 图标库
import { DollarOutlined, ThunderboltOutlined, MessageOutlined, ClockCircleOutlined } from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer, ProTable, ProColumns, ActionType } from '@ant-design/pro-components';

// 5. 工具库
import dayjs from 'dayjs';

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { TokenUsageLog } from '@/services/generated';

const TokenUsageStats: React.FC = () => {
  const [period, setPeriod] = useState<string>('month');
  const actionRef = useRef<ActionType>();

  // 获取使用记录列表
  const fetchUsageLogs = async (params: any) => {
    try {
      await autoLoginInDev();
      const response = await apiClients.aiChat.aiChatTokenUsageList({
        page: params.current,
        pageSize: params.pageSize,
        user: params.user,
        aiModel: params.ai_model,
        conversation: params.conversation,
      });
      return {
        data: response.data?.items || [],
        success: true,
        total: response.data?.total || 0,
      };
    } catch (error) {
      console.error('获取Token使用记录失败:', error);
      return { data: [], success: false, total: 0 };
    }
  };

  // 获取统计数据
  const [statsData, setStatsData] = useState<any>(null);
  const [loading, setLoading] = useState(false);

  const fetchStatsData = async () => {
    try {
      setLoading(true);
      await autoLoginInDev();
      const response = await apiClients.aiChat.aiChatTokenUsageStatsRetrieve({
        period: period,
      });
      console.log('Token统计数据响应:', response);
      setStatsData(response.data);
    } catch (error) {
      console.error('获取Token统计数据失败:', error);
      setStatsData(null);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStatsData();
  }, [period]);

  // 表格列定义
  const columns: ProColumns<TokenUsageLog>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: '对话标题',
      dataIndex: 'conversation_title',
      ellipsis: true,
      search: false,
    },
    {
      title: 'AI模型',
      dataIndex: 'ai_model_name',
      search: false,
      render: (_, record) => (
        <Tag color="blue">{record.ai_model_name || '未知'}</Tag>
      ),
    },
    {
      title: '输入Token',
      dataIndex: 'input_tokens',
      search: false,
      render: (value) => (
        <Tag color="green">{value || 0}</Tag>
      ),
    },
    {
      title: '输出Token',
      dataIndex: 'output_tokens',
      search: false,
      render: (value) => (
        <Tag color="orange">{value || 0}</Tag>
      ),
    },
    {
      title: '总Token',
      dataIndex: 'total_tokens',
      search: false,
      sorter: true,
      render: (value) => (
        <Tag color="purple">{value || 0}</Tag>
      ),
    },
    {
      title: '费用',
      dataIndex: 'cost',
      search: false,
      render: (_, record) => {
        // 简单估算，实际应该根据模型定价
        const estimatedCost = (record.total_tokens || 0) * 0.000001;
        return `$${estimatedCost.toFixed(6)}`;
      },
    },
    {
      title: '使用时间',
      dataIndex: 'created_at',
      valueType: 'dateTime',
      search: false,
      sorter: true,
      render: (_, record) => {
        if (!record.created_at) return '-';
        const date = dayjs(record.created_at);
        return date.isValid() ? date.format('MM-DD HH:mm') : '-';
      },
    },
  ];

  return (
    <PageContainer
      header={{
        title: 'Token使用统计',
        subTitle: '查看Token使用情况和费用统计',
      }}
    >
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总Token使用量"
              value={statsData?.total_tokens || 0}
              prefix={<ThunderboltOutlined />}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="输入Token"
              value={statsData?.input_tokens || 0}
              prefix={<MessageOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="输出Token"
              value={statsData?.output_tokens || 0}
              prefix={<MessageOutlined />}
              valueStyle={{ color: '#fa8c16' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总费用"
              value={statsData?.total_cost || 0}
              prefix={<DollarOutlined />}
              precision={6}
              valueStyle={{ color: '#cf1322' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 统计周期选择 */}
      <Card style={{ marginBottom: 24 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <span>统计周期：</span>
          <Select
            value={period}
            onChange={setPeriod}
            style={{ width: 120 }}
            options={[
              { label: '最近一天', value: 'day' },
              { label: '最近一周', value: 'week' },
              { label: '最近一月', value: 'month' },
            ]}
          />
        </div>
      </Card>

      {/* 使用记录表格 */}
      <ProTable<TokenUsageLog>
           scroll={{x: 'max-content'}}
        headerTitle="Token使用记录"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        request={fetchUsageLogs}
        columns={columns}
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
        }}
      />
    </PageContainer>
  );
};

export default TokenUsageStats;
